package com.xcity.robot.net;

import java.net.InetSocketAddress;
import java.util.Date;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.xcity.robot.net.packet.PacketHandler;
import com.xcity.robot.net.util.SessionUtils;
import com.xcity.robot.net.websocket.HandshakeListener;

import naga.x.net.impl.pomelo.PomeloPacket;
import naga.x.util.IOUtils;
import naga.x.util.StringUtils;

public class NetIoHandler extends IoHandlerAdapter {
	
	static final String HEADER_SEPARATOR = "\r\n";
	static final String HEADER0 =
			"GET / HTTP/1.1" + HEADER_SEPARATOR
			+ "Host: ";
	static final String HEADER1 =
			"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0" + HEADER_SEPARATOR
			+ "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" + HEADER_SEPARATOR
			+ "Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3" + HEADER_SEPARATOR
			+ "Accept-Encoding: gzip, deflate" + HEADER_SEPARATOR
			+ "Sec-WebSocket-Version: 13" + HEADER_SEPARATOR
			+ "Origin: http://127.0.0.1" + HEADER_SEPARATOR
			+ "Sec-WebSocket-Extensions: permessage-deflate" + HEADER_SEPARATOR
			+ "Sec-WebSocket-Key: f9wxSs+cfvOmdTWD0dKuzw==" + HEADER_SEPARATOR
			+ "Connection: keep-alive, Upgrade" + HEADER_SEPARATOR
			+ "Pragma: no-cache" + HEADER_SEPARATOR
			+ "Cache-Control: no-cache" + HEADER_SEPARATOR
			+ "Upgrade: websocket" + HEADER_SEPARATOR;
	
//	public static void main(String[] args) {
//		byte[] b = Base64.getDecoder().decode("f9wxSs+cfvOmdTWD0dKuzw==");
//		System.out.println(StringUtils.bytesToString(b, IOUtils.UTF8));
//	}
	
	public void sessionCreated(IoSession session) throws Exception {
//		session.setAttribute(SessionUtils.HANDSHAKE_LISTENER, HandshakeListener.WEBSOCKET_HANDSHAKE);
		session.setAttribute(SessionUtils.POMELO_HANDSHAKE_LISTENER, HandshakeListener.POMELO_HANDSHAKE);
		session.setAttribute(SessionUtils.SESSION, new Session(session));
		InetSocketAddress addr = (InetSocketAddress) session.getRemoteAddress();
		String handshake =
				HEADER0 + addr.getHostName() + ":" + addr.getPort() + HEADER_SEPARATOR
				+ HEADER1;
		session.write(IoBuffer.wrap(StringUtils.stringToBytes(handshake, IOUtils.UTF8)));
		System.out.println("---try handshake---" + new Date());
    }

    /**
     * {@inheritDoc}
     */
    public void sessionClosed(IoSession session) throws Exception {
    	System.out.println("-----session closed-----" + session);
    }

    /**
     * {@inheritDoc}
     */
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        // Empty handler
    }

    /**
     * {@inheritDoc}
     */
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    	super.exceptionCaught(session, cause);
    }

    /**
     * {@inheritDoc}
     */
    public void messageReceived(IoSession session, Object message) throws Exception {
    	if (!(message instanceof PomeloPacket)) {
//    		System.out.println("WARNING::: messageReceived but not PomeloPacket: " + message);
    		return;
    	}
    	PomeloPacket packet = (PomeloPacket) message;
    	Session sess = (Session) session.getAttribute(SessionUtils.SESSION);
    	PacketHandler handler = sess.getHandler(packet);
    	if (handler != null) {
    		handler.handle(sess, packet);
    	} else {
//    		System.err.println("messageReceived but no handler: " + packet.getData());
    	}
    }

    /**
     * {@inheritDoc}
     */
    public void messageSent(IoSession session, Object message) throws Exception {
    }
}
